package tom.webflux.service;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import tom.webflux.model.User;

import java.util.Map;

/**
 * web-flux应用返回的是Mono和Flux
 * @author ZHUFEIFEI
 */
@Slf4j
@Service
public class UserService {

    private Map<Long, User> memStore ;

    public UserService() {
        this.memStore = Maps.newHashMap();
        this.memStore.put(1L, new User(1L, "tom"));
        this.memStore.put(2L, new User(2L, "cat"));
        this.memStore.put(3L, new User(3L, "dog"));
    }

    public Mono<User> findById(Long id) {
        return Mono.just(this.memStore.get(id));
    }

    public Flux<User> findAll() {
        return Flux.fromIterable(this.memStore.values());
    }

    public void create(User user) {
        log.info("add user : {}", user);
        this.memStore.put(user.getId(), user);
    }

    public void delete(Long id) {
        log.info("remove user : {}", id);
        this.memStore.remove(id);
    }

}
